package com.mo.admin.common.utils;


import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

public class ResponseWriterUtils {

    // 向客户端响应输出字符串
    public static void writeResponse(HttpServletResponse response, String content) {
        if (response == null || content == null) {
            return;
        }
        try (PrintWriter writer = response.getWriter()) {
            writer.write(content);
            writer.flush();  // 确保内容被写出
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 向客户端响应输出 JSON 格式内容
    public static void writeJsonResponse(HttpServletResponse response, String jsonContent) {
        if (response == null || jsonContent == null) {
            return;
        }
        response.setContentType("application/json;charset=UTF-8");
        try (PrintWriter writer = response.getWriter()) {
            writer.write(jsonContent);
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 向客户端响应输出 HTML 格式内容
    public static void writeHtmlResponse(HttpServletResponse response, String htmlContent) {
        if (response == null || htmlContent == null) {
            return;
        }
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter writer = response.getWriter()) {
            writer.write(htmlContent);
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 向客户端响应输出 XML 格式内容
    public static void writeXmlResponse(HttpServletResponse response, String xmlContent) {
        if (response == null || xmlContent == null) {
            return;
        }
        response.setContentType("application/xml;charset=UTF-8");
        try (PrintWriter writer = response.getWriter()) {
            writer.write(xmlContent);
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 设置响应的 HTTP 状态码
    public static void setResponseStatus(HttpServletResponse response, int statusCode) {
        if (response != null) {
            response.setStatus(statusCode);
        }
    }
}
